﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace QuaManSys.Rights
{
    public partial class RolesManPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "window.parent.changewin();", true);
            strinfo.InnerHtml = "";
            strinfo.Visible = false;
            if (!IsPostBack)
            {
                pnlCreateRole.Visible = false;
                btn_search.Attributes.Add("onclick", "return Btn_Search();");
                InitRolesInfo();
            }
        }

        protected void InitRolesInfo()
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {
                    string strID = txt_name.Text.Trim();
                    List<SysRole> rolesInfo;
                    if (strID == "")
                    {
                        var query = from p in context.SysRole
                                    select p;
                        rolesInfo = query.ToList();
                    }
                    else
                    {
                        var query = from p in context.SysRole
                                    where (p.Name == strID)
                                    orderby p.Id
                                    select p;
                        rolesInfo = query.ToList();
                    }
                    RoleList.DataSource = rolesInfo;
                    RoleList.DataBind();
                    
                }
                catch
                {

                }
            }
        }
        /// <summary>
        /// 绑定用户数据
        /// </summary>
        protected void BindOrder()
        {
            using (var entity = new QuaManSysEntities())
            {
                var queryRoles = from q in entity.SysRole
                                 select q;
                RoleList.DataSource = queryRoles;
                RoleList.DataBind();
            }
            
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            pnlSearch.Visible = true;
            if (txt_name.Text != "")
            {
                InitRolesInfo();
            }
        }

        protected void btn_create_Click(object sender, EventArgs e)
        {
            pnlCreateRole.Visible = true;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (var entity = new QuaManSysEntities())
            {
                try
                {
                    string roleId = txtRoleId.Text.Trim();
                    if (roleId == "")
                        throw new Exception();
                    string roleName = txtRoleName.Text.Trim();
                    if (roleName == "")
                        throw new Exception();

                    SysRole aNewRole = new SysRole
                    {
                        Id = roleId,
                        Name = roleName,
                        Description = txtRoleDescription.Text.Trim(),
                        CreateTime = DateTime.Now,
                    };
                    entity.SysRole.Add(aNewRole);
                    //entity.SaveChanges();

                    var queryParentMenu = (from q in entity.SysMenu
                                           where q.ParentId == null
                                           select q).Distinct();
                    foreach (var item in queryParentMenu)
                    {
                        SysMenuSysRoleSysOperation aNew = new SysMenuSysRoleSysOperation
                        {
                            SysMenuId = item.Id,
                            SysRoleId = roleId,
                        };
                        entity.SysMenuSysRoleSysOperation.Add(aNew);
                        //entity.SaveChanges();
                    }
                    entity.SaveChanges();
                    pnlCreateRole.Visible = false;
                    InitRolesInfo();
                }
                catch
                {
                    string errorMessage = "增加角色失败,请重新尝试";
                    Response.Write("<script>alert('" + errorMessage + "')</script>");
                }
            }
        }

        /// <summary>
        /// 删除操作
        /// </summary>
        protected void UserList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName.ToString())
            {
                case "Del":
                    if (DeleteRole(e.CommandArgument.ToString()))
                    {
                        InitRolesInfo();
                    }
                    else
                    {
                        strinfo.InnerHtml = errinfo("删除操作失败!");
                        strinfo.Visible = true;
                    }
                    break;
                //case "Grant":
                //    string[] s = e.CommandArgument.ToString().Split(',');
                //    Response.Redirect("UserGrant.aspx?uid=" + s[0] + "&name=" + s[1]);
                //    break;
            }
        }

        private bool DeleteRole(string p)
        {
            bool delRoleOrNot = false;
            using (var entity = new QuaManSysEntities())
            {

                var rolesPerson = from q in entity.SysRole
                                  join r in entity.SysRoleSysPerson
                                  on q.Id equals r.SysRoleId
                                  where r.SysRoleId == p
                                  select r;
                foreach (var item in rolesPerson)
                {
                    entity.SysRoleSysPerson.Remove(item);
                }

                var rolesDepartment = from q in entity.SysRole
                                      join r in entity.SysRoleSysDept
                                      on q.Id equals r.Dept
                                      where q.Id == p
                                      select r;
                foreach (var item in rolesPerson)
                {
                    entity.SysRoleSysPerson.Remove(item);
                }

                var rolesMenuOperation = from q in entity.SysRole
                                         join r in entity.SysMenuSysRoleSysOperation
                                         on q.Id equals r.SysRoleId
                                         where r.SysRoleId == p
                                         select r;
                foreach (var item in rolesMenuOperation)
                {
                    entity.SysMenuSysRoleSysOperation.Remove(item);
                }

                SysRole aRole = (from q in entity.SysRole
                            where q.Id == p
                            select q).Single();
                entity.SysRole.Remove(aRole);

                entity.SaveChanges();
                delRoleOrNot = true; 
            }
            return delRoleOrNot;
        }

        public static string errinfo(string s)
        {
            return "<ul><li>" + s + "</li></ul>";
        }
    }
}